<template>
  <div class="spot-list">
    <el-scrollbar>
      <div class="list-container" 
        v-infinite-scroll="loadMore" 
        :infinite-scroll-disabled="scrollDisabled"  
        infinite-scroll-distance="10">
        <SpotItem v-for="spot in spots" :key="spot.attractionId" :spot="spot"
          @click="handleSpotClick(spot.attractionId)"
          @add="handleAddSpot" />
        <div v-if="loading" class="loading-more">
          <el-spinner />
        </div>

        <div v-if="!hasMore && spots.length > 0" class="no-more">
          没有更多数据了
        </div>
      </div>
    </el-scrollbar>
    <AttractionDetail
    v-model:visible="detailVisible"
    :attraction-id="selectedAttractionId"
    :attraction="selectedAttraction"
    @close="handleDetailClose"
    @addSpot="handleAddSpot"
  />
  </div>
</template>

<script setup  lang="ts">
import { ref, onMounted, watch,computed} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import SpotItem from './SpotItem.vue'
import { calculateDistance } from '@/utils/distance'
import { useLocationStore } from '@/stores/LocationStore'
import AttractionDetail from '../attractionDetail/AttractionDetail.vue'
import {
  getAttractionByRegion,
  getAttractionByRating,
  getAttractionBySelectCount,
  getAttractionByDistance,
  getAttractionByHot,
  searchAttraction
} from '@/api/Attraction'

// 默认地区ID（武汉）
const DEFAULT_REGION_ID = '260'

const spots = ref([])
const page = ref(1)
const loading = ref(false)
const hasMore = ref(true)
const filterType = ref('region')
const currentRegionId = ref(0)
const currentQuery = ref('')
const userLocation = ref(null)
const locationStore = useLocationStore()
const router = useRouter()
const detailVisible = ref(false)
const selectedAttraction = ref(null)
const selectedAttractionId = ref<number | null>(null)
const emit = defineEmits(['addSpot'])
const attractionDetailRef = ref<InstanceType<typeof AttractionDetail>>()

const resetList = () => {
  spots.value = []
  page.value = 1
  hasMore.value = true
  loading.value = false
}
const props = defineProps({
  mapLoaded: {
    type: Boolean,
    default: false
  }
})
const processSpots = (newSpots) => {
  if ( locationStore.currentPosition) {
    const { latitude: userLat, longitude: userLon } = locationStore.currentPosition

    return newSpots.map(spot => ({
      ...spot,
      distance: calculateDistance(
        userLat,
        userLon,
        spot.latitude,
        spot.longitude
      )
    }))
  }
  else{
    return newSpots.map(spot => ({
      ...spot,
      distance: null
    }))
  }
}
const handleAddSpot = (spot) => {
  emit('addSpot', {
    attractionId: spot.attractionId,
    regionId: spot.regionId,
    name: spot.name,
    description: spot.description,
    address: spot.address,
    image: spot.image,
    latitude: spot.latitude,
    longitude: spot.longitude,
    priceRange: spot.priceRange,
    openingHours: spot.openingHours,
    likeCount: spot.likeCount,
    commentCount: spot.commentCount,
    attractionRating: spot.attractionRating,
    recommendedVisitTime: spot.recommendedVisitTime,
    recommendedVisitSeason: spot.recommendedVisitSeason,
    selectCount: spot.selectCount,
    duration: spot.recommendedVisitTime ? parseInt(spot.recommendedVisitTime) : 120,
    aiSuggestion: '暂无建议'
  })
}
// 修改点击处理函数
const handleSpotClick = (attractionId: number) => {
  // 从现有列表中查找景点信息
  const spot = spots.value.find(s => s.attractionId === attractionId)
  if (spot) {
    selectedAttraction.value = {
      ...spot,
      // 转换数据格式以匹配详情页需要的格式
      attractionId: spot.attractionId,
      name: spot.name,
      description: spot.description,
      address: spot.address,
      image: spot.image,
      openingHours: spot.openingHours,
      priceRange: spot.priceRange,
      likeCount: spot.likeCount,
      attractionRating: spot.attractionRating,
      recommendedVisitTime: spot.recommendedVisitTime,
      recommendedVisitSeason: spot.recommendedVisitSeason
    }
    selectedAttractionId.value = attractionId
    detailVisible.value = true
  }
}
const handleDetailClose = () => {
  detailVisible.value = false
  selectedAttractionId.value = null
}

//浏览到底部时触发加载更多
const loadMore = async () => {
  console.log('加载更多') // 调试日志
  if (loading.value || !hasMore.value || !props.mapLoaded) {
    console.log('跳过加载:', {
      loading: loading.value,
      hasMore: hasMore.value,
      mapLoaded: props.mapLoaded
    })
    return
  }
  
  loading.value = true
  try {
    if (filterType.value === 'region' && !currentRegionId.value) {
      loading.value = false
      return
    }

    let response
    const regionId = currentRegionId.value || null

    switch (filterType.value) {
      case 'region':
        response = await getAttractionByRegion(regionId, page.value, 10)
        break
      case 'rating':
        response = await getAttractionByRating(page.value, 10, regionId)
        break
      case 'popularity':
        response = await getAttractionBySelectCount(page.value, 10, regionId)
        break
      case 'hot':
        response = await getAttractionByHot(page.value, 10, regionId)
        break
      case 'distance':
        if (!locationStore.currentPosition) {
          ElMessage.error('无法获取位置信息')
          return
        }
        response = await getAttractionByDistance(
          page.value,
          10,
          locationStore.currentPosition.latitude,
          locationStore.currentPosition.longitude
        )
        break
      case 'search':
        if (!currentQuery.value) {
          loading.value = false
          return
        }
        response = await searchAttraction(page.value, 10, currentQuery.value)
        break
    }
    if (response?.data) {
      const newSpots = Array.isArray(response.data) ? response.data : response.data.items || []
      // 处理距离信息
      const processedSpots = processSpots(newSpots)
      spots.value.push(...processedSpots)
      hasMore.value = newSpots.length === 10
      page.value++
    }
  } catch (error) {
    console.error('加载景点失败:', error)
    ElMessage.error('加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

//处理筛选变化
const handleFilterChange = async ({ type, regionId, query }) => {
  console.log('Filter changed:', { type, regionId, query }) // 调试日志

  if (!props.mapLoaded) {
    console.log('地图未加载完成，跳过筛选')
    return
  }

  filterType.value = type
  currentRegionId.value = regionId
  currentQuery.value = query
  if (location) {
    userLocation.value = location
  }
  resetList()
  await loadMore() // 确保等待加载完成
}

//在获取到位置后加载默认景点
const loadDefaultSpots = () => {
  // 确保地图已加载且已获取位置
  if (!props.mapLoaded || !locationStore.currentPosition) {
    console.log('地图或位置未就绪，跳过默认加载')
    return
  }

  console.log('加载默认景点列表')
  handleFilterChange({
    type: 'region',
    regionId: DEFAULT_REGION_ID,
    query: ''
  })
}
const scrollDisabled = computed(() => {
  return loading.value || !hasMore.value || !props.mapLoaded
})

watch(
  () => locationStore.currentPosition,
  (newPosition) => {
    if (newPosition && filterType.value === 'distance') {
      resetList()
      loadMore()
    }
  }
)

defineExpose({
  handleFilterChange,
  loadDefaultSpots,
  resetList
})

</script>

<style scoped>
.spot-list {
  flex: 1;
  overflow: hidden;
  margin-top: 10px;
}

.list-container {
  padding: 12px;
}

.loading-more {
  padding: 20px 0;
}

.no-more {
  text-align: center;
  color: #999;
  padding: 20px 0;
  font-size: 14px;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>